package main.java.com.epam;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class MyClassLoader extends ClassLoader{

	private InputStream inputStream = null;
	private File classFile = null;
	private String className = null;
	private String classFileToLoad;
	byte[] b;

	public void setup(String classFileToLoad) throws FileNotFoundException {
		this.classFileToLoad = classFileToLoad;
		classFile = new File(classFileToLoad + ".class");
		className = classFileToLoad.substring(classFileToLoad.lastIndexOf(File.separator) + 1, classFileToLoad.length());
		inputStream = new BufferedInputStream( new FileInputStream(classFile));
		b = new byte[(int)classFile.length()];
		
		//reading file
		try {
			inputStream.read(b);
		} catch(IOException ioe){

			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}


	}

	public Class<?> findClass() throws ClassNotFoundException {

		if(!classFile.isFile()){
			throw new ClassNotFoundException("Class not found " + classFileToLoad);
		}

		try { 
			Class<?> c = defineClass(className, b, 0, b.length);
			return c;

		} catch(ClassFormatError e){
			e.printStackTrace();
			throw new ClassNotFoundException("Class format problems:" + e.getMessage());
		}//catch 
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public void setClassFile(File classFile) {
		this.classFile = classFile;
	}

	public void setB(byte[] b) {
		this.b = b;
	}

	public void setClassName(String className) {
		this.className = className;
	}

}
